package com.testapp.bluetoothtest08;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocationClient;
import com.testapp.bluetoothtest08.Constant.Constants;
import com.testapp.bluetoothtest08.Controller.BlueToothController;
import com.testapp.bluetoothtest08.File.Cipher;
import com.testapp.bluetoothtest08.File.CodeFile;
import com.testapp.bluetoothtest08.File.DeviceFile;
import com.testapp.bluetoothtest08.File.Statement;
import com.testapp.bluetoothtest08.File.Token;
import com.testapp.bluetoothtest08.File.UserName;
import com.testapp.bluetoothtest08.Http.OkHttp;
import com.testapp.bluetoothtest08.Judge.IsYellow;
import com.testapp.bluetoothtest08.My.MyFragment;
import com.testapp.bluetoothtest08.Util.RequestCodeGenerateUtil;
import com.testapp.bluetoothtest08.cipher.UserCipherService;
import com.testapp.bluetoothtest08.cipher.impl.UserCipherServiceImpl;


import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button login, register;
    private EditText uname,password;
    private String username,pass;
    private Intent intent = null;
    private String cipher;


    JSONObject obj = new JSONObject();
    OkHttp http = new OkHttp();
    UserCipherService userCipherService = new UserCipherServiceImpl();
    private BlueToothController mController=new BlueToothController();
    public List<BluetoothDevice> find =new ArrayList<>();



    //发现设备
    Thread findDevice = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true){
                try {
                    find.clear();
                    mController.find();
                    Thread.sleep(10000);
                    new DeviceFile().writeDevices(find);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });


    Thread requestServerChangeCode = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true){
                try{
                    new RequestCodeGenerateUtil().requestUpdate();
                    Thread.sleep(1000*60);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    });



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
//        String zuobi = "{\"a\":\"252343675788361504772280818824690321641701846601221603762420640291605906459995\",\"c\":\"871150770870580837425903444924\",\"p\":\"1746856145997762929285190925031575852766588676798700695333540\",\"secList\":[\"871150770870580837425903444924\",\"1070112537255731684785\",\"1152913760569457945690\",\"1650391937913881051919656581060900368401866529973480541780082\",\"2115720880121307617158\",\"819\",\"802\",\"706\",\"726120022303187809265\"],\"t2\":\"1045608342865575932373\",\"y\":\"1645504557321206042154969182557350504982735156513387973351218649\"}";
//        new Cipher().write(zuobi);
//        System.out.println("new --- >" + new Cipher().read());
    }

    @Override
    protected void onStart() {
        super.onStart();
        Constants.token = new Token().read();
        System.out.println("Local Token  ----> "+new Token().read());
        if(Constants.token!=null&&Constants.token!=""){
            Constants.login=true;
        }else {
            Constants.login=false;
        }

        if(Constants.login){
            intent = new Intent(MainActivity.this, HomeActivity.class);
            Constants.login=true;
            startActivity(intent);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void init() {
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        uname = findViewById(R.id.username);
        password = findViewById(R.id.password);

        login.setOnClickListener(this);
        register.setOnClickListener(this);

        //让用户获取权限
        requestPermissions(new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        },1);

        //开启地图定位
        AMapLocationClient.updatePrivacyAgree(getApplicationContext(), true);
        AMapLocationClient.updatePrivacyShow(getApplicationContext(), true, true);
        //蓝牙权限+广播注册
        getPermission();
        registerBlueToothReceiver();

        //打开蓝牙+设置蓝牙永久打开
        mController.turnOn();
        setDiscoverableTimeout();
        mController.setVisible(MainActivity.this);



        //写编码
//        new CodeFile().createCode();
        code.start();

        //发现设备
        findDevice.start();

        //定时请求是否需要更新二维码
        requestServerChangeCode.start();



        Constants.token = new Token().read();
    }

    Thread code = new Thread(new Runnable() {
        @Override
        public void run() {
            while(true){
                try {
                    new CodeFile().createCodeOne();
                    Thread.sleep(30*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.login:
                login();
                break;
            case R.id.register:
                intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }
    public void login(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                intent = new Intent(MainActivity.this, HomeActivity.class);
                username =uname.getText().toString();
                pass = password.getText().toString();
                try {
                    obj.put("username",username);
                    obj.put("password",pass);
                    String result = http.httpPost(Constants.LOGIN_URL,obj.toJSONString());
                    System.out.println("服务器返回的结果 ----> "+result);
                    JSONObject O = JSONObject.parseObject(result);
                    //得到token
                    if(O!=null){
                        Constants.token = O.getString("data");
                        System.out.println("服务器下发的token ----> "+Constants.token);
                    }

                    if(Constants.token!=null){
                        //写入token
                        new Token().write(Constants.token);
                        uname.setText("");
                        password.setText("");

                        //获取状态
                        String state = http.httpGet(Constants.GET_INFO_URL);
                        JSONObject s = JSONObject.parseObject(state);
                        System.out.println("码的状态 ----> "+s);
                        String data = s.getString("data");
                        JSONObject d = JSONObject.parseObject(data);
                        int statement = (int) d.get("codeColor");
                        switch(statement){
                            case 0:
                                new Statement().write("正常者");
                                break;
                            case 1:
                                new Statement().write("接触者");
                                break;
                            case 2:
                                new Statement().write("确诊者");
                                break;
                        }
                        //保存本地 username
                        String Uname = d.getString("name");
                        System.out.println("名字 ------> "+Uname);
                        new UserName().write(Uname);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                Constants.login=true;
                                startActivity(intent);
                            }
                        });
                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    //注册广播
    private void registerBlueToothReceiver(){
        IntentFilter filter1=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter1);
        IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter2);
        IntentFilter filter3=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(mReceiver,filter3);
        IntentFilter filter4=new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        registerReceiver(mReceiver,filter4);
    }
    //注册广播
    private BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action =intent.getAction();
            if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)){
                find.clear();
            }else if(action.equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                find.add(device);
//                System.out.println(device.getName()+"==========>"+device.getAddress());
            }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                System.out.println("搜索完毕！");
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        findDevice.interrupt();
        requestServerChangeCode.interrupt();
        code.interrupt();
        super.onDestroy();
    }

    //======================================================================================================
    //蓝牙永久可见
    public static void setDiscoverableTimeout() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        try {
            Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
            setDiscoverableTimeout.setAccessible(true);
            Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
            setScanMode.setAccessible(true);
            setDiscoverableTimeout.invoke(adapter, 0);
            setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
            Log.e("Status","open Bluetooth search");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("error","setDiscoverableTimeout failure:" + e.getMessage());
        }
    }

    /**
     * 解决：无法发现蓝牙设备的问题
     *
     * 对于发现新设备这个功能, 还需另外两个权限(Android M 以上版本需要显式获取授权,附授权代码):
     */
    private final int ACCESS_LOCATION=1;
    @SuppressLint("WrongConstant")
    private void getPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            int permissionCheck = 0;
            permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionCheck += this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                //未获得权限
                this.requestPermissions( // 请求授权
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION},
                        ACCESS_LOCATION);// 自定义常量,任意整型
            }
        }
    }

    /**
     * 请求权限的结果回调。每次调用 requestpermissions（string[]，int）时都会调用此方法。
     * @param requestCode 传入的请求代码
     * @param permissions 传入permissions的要求
     * @param grantResults 相应权限的授予结果:PERMISSION_GRANTED 或 PERMISSION_DENIED
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case ACCESS_LOCATION:
                if (hasAllPermissionGranted(grantResults)) {
                    Log.i("TAG", "onRequestPermissionsResult: 用户允许权限");
                } else {
                    Log.i("TAG", "onRequestPermissionsResult: 拒绝搜索设备权限");
                }
                break;
        }
    }

    private boolean hasAllPermissionGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }
//======================================================================================================

}